package top.lingkang.finalvalidated.handle;

import top.lingkang.finalvalidated.constraints.Min;
import top.lingkang.finalvalidated.core.FinalValidatorFactory;
import top.lingkang.finalvalidated.error.ValidatedException;
import top.lingkang.finalvalidated.utils.FinalValidatorUtils;

/**
 * @author lingkang
 * Created by 2024/1/26
 */
public class MinHandle extends ValidHandle {
    private final String errorStr;
    private final Min min;

    public MinHandle(ValidVal validVal, Min min) {
        super(validVal, min);
        this.min = min;

        if (FinalValidatorUtils.isNotEmpty(min.message())) {
            errorStr = min.message();
        } else if (FinalValidatorUtils.isNotEmpty(validVal.getTag())) {
            errorStr = FinalValidatorFactory.message.getProperty("Min")
                    .replace("{attrName}", validVal.getTag())
                    .replace("{value}", Long.toString(min.value()));
        } else {
            errorStr = FinalValidatorFactory.message.getProperty("Min")
                    .replace("{attrName}", validVal.getName())
                    .replace("{value}", Long.toString(min.value()));
        }
    }

    @Override
    public void valid(Object target) {
        Object o = validVal.getValGet().get(target);
        if (o == null || FinalValidatorUtils.notMin(o, min.value())) {
            throw new ValidatedException(errorStr, validVal);
        }
    }

    @Override
    public Class<?>[] getGroups() {
        return min.groups();
    }
}
